import React, { useRef, useState, useEffect } from "react";
import "./index.scss";

const ChentsMob = () => {
  const scrollRef = useRef(null);
  const [showLeftArrow, setShowLeftArrow] = useState(false);
  const [showRightArrow, setShowRightArrow] = useState(true);

  // 滚动检查显示哪个箭头
  const checkArrows = () => {
    const el = scrollRef.current;
    if (!el) return;
    const { scrollLeft, scrollWidth, clientWidth } = el;

    setShowLeftArrow(scrollLeft > 5); // 滚动距离大于5才显示左箭头
    setShowRightArrow(scrollLeft + clientWidth < scrollWidth - 5); // 还能往右滚动才显示右箭头
  };

  useEffect(() => {
    checkArrows();
    const el = scrollRef.current;
    if (!el) return;
    el.addEventListener("scroll", checkArrows);
    return () => el.removeEventListener("scroll", checkArrows);
  }, []);

  // 点击右箭头，往右滚动 120px（卡片宽度+间距）
  const scrollRight = () => {
    scrollRef.current.scrollBy({ left: 132, behavior: "smooth" });
  };

  // 点击左箭头，往左滚动 120px
  const scrollLeft = () => {
    scrollRef.current.scrollBy({ left: -132, behavior: "smooth" });
  };

  return (
    <div className="chents-mob">
      {showLeftArrow && (
        <button className="arrow-btn left" onClick={scrollLeft}>
          &#10094;
        </button>
      )}
      <div className="scroll-wrapper" ref={scrollRef}>
        {Array.from({ length: 15 }).map((_, i) => (
          <div className="sorllor" key={i}>
            {i + 1}
          </div>
        ))}
      </div>
      {showRightArrow && (
        <button className="arrow-btn right" onClick={scrollRight}>
          &#10095;
        </button>
      )}
    </div>
  );
};

export default ChentsMob;
